package com.zzq.my.jetpacks.jectpackapp.kt

import android.annotation.SuppressLint
import android.app.Activity
import android.content.*
import android.content.pm.PackageInfo
import android.content.res.Resources
import android.graphics.Point
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.net.Uri
import android.os.Build
import android.util.TypedValue
import android.view.WindowManager
import androidx.annotation.RequiresPermission

@Desc("网络是否连接", "v1.0.0")
@RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
fun Context.isConnected(): Boolean {
    val conn = this.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    val networkInfo = conn.activeNetworkInfo ?: return false
    return networkInfo.isAvailable && networkInfo.isConnected
}

@Desc("从Context获取Activity", "v1.0.0")
val Context.activity: Activity?
    get() {
        if (this is Activity) return this

        var context = this
        while (context is ContextWrapper) {
            if (context is Activity) {
                return context
            }
            context = context.baseContext
        }
        return null
    }

@Desc("获取屏幕宽度", "v1.0.0")
val Context.screenWidth
    get() = Resources.getSystem().displayMetrics.widthPixels

@Desc("获取屏幕高度", "v1.0.0")
val Context.screenHeight
    get() = Resources.getSystem().displayMetrics.heightPixels

@Desc("打开网页", "v1.0.0", "v1.0.2", "去掉try")
fun Context.openWeb(url: String) {
    val intent = Intent().apply {
        action = "android.intent.action.VIEW"
        val uri = Uri.parse(url)
        data = uri
    }
    this.startActivity(intent)
}

@Desc("发送Email", "v1.0.0", "v1.0.2", "去掉try")
fun Context.sendEmail(
    email: String,
    subject: String? = ""
) {
    val uri = Uri.parse("mailto:$email")
    val intent = Intent(Intent.ACTION_SENDTO, uri).apply {
        putExtra(Intent.EXTRA_CC, email)
        putExtra(Intent.EXTRA_SUBJECT, subject)
    }
    this.startActivity(intent)
}

@Desc("打开应用商店", "v1.0.0", "v1.0.2", "去掉try")
fun Context.openMarket(
    packageName: String = this.packageName
) {
    val uri = Uri.parse("market://details?id=${packageName}")
    val intent = Intent(Intent.ACTION_VIEW, uri)
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    this.startActivity(intent)
}

@Desc("复制文本", "v1.0.0")
fun Context.copyText(
    text: String,
    label: String
) {
    val cm = this.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
    val clipData = ClipData.newPlainText(label, text)
    cm.setPrimaryClip(clipData)
}

@Desc("复制文本2", "v1.0.0")
fun Context.copyText(
    text: String
) {
    val cm = this
        .getSystemService(Context.CLIPBOARD_SERVICE) as android.text.ClipboardManager
    cm.text = text
}

//----------NetWork----------

/**
 * 打开网络设置
 */
fun Context.openWirelessSettings() {
    startActivity(Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
}

/**
 * 网络是否连接
 */


/**
 * 判断网络是否是移动数据
 */
fun Context.isMobileData(): Boolean {
    var info = this.getActiveNetworkInfo()
    return (null != info
            && info.isAvailable
            && info.type == ConnectivityManager.TYPE_MOBILE)
}

/**
 * 退回到桌面
 */
fun Context.startHomeActivity() {
    val homeIntent = Intent(Intent.ACTION_MAIN)
    homeIntent.addCategory(Intent.CATEGORY_HOME)
    startActivity(homeIntent)
}


@SuppressLint("MissingPermission")
private fun Context.getActiveNetworkInfo(): NetworkInfo {
    val manager = this.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    return manager.activeNetworkInfo!!
}


/**
 * px转dp
 */
fun Context.px2dip(px: Float): Float = px / resources.displayMetrics.density + 0.5f
fun Context.px2dip(px: Int): Int = px2dip(px.toFloat()).toInt()



/**
 * 获取app版本号的code V1.0.0
 */
inline val Context.versionCode
    get() = try {
        this.packageManager.getPackageInfo(this.packageName, 0).getVersionCode()
    } catch (e: Exception) {
        0L
    }

/**
 * 获取app版本号的名称
 */
@Suppress("HasPlatformType")
inline val Context.versionName
    get() = try {
        this.packageManager.getPackageInfo(this.packageName, 0).versionName
    } catch (e: Exception) {
        "unknown"
    }


@Suppress("DEPRECATION")
@SuppressLint("NewApi")
fun PackageInfo.getVersionCode(): Long {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) this.longVersionCode else this.versionCode.toLong()
}



